<template>
    <div>
        <div class="main-head has-radios flex-between container-fluid">
            <div class="title">
                <h1>{{ $t('pro.campaignsServe.title') }}</h1>
            </div>
        </div>

        <div class="content container-fluid">
            <div class="portlet">
                <div class="tools">
                    <div class="tools-left">
                        <!--<a-select defaultValue="All" style="min-width: 120px;">
                            <a-select-option value="All">{{ $t('pro.admin.All') }}</a-select-option>
                            <a-select-option value="Active">{{ $t('pro.campaignsServe.open') }}</a-select-option>
                            <a-select-option value="Not Active">{{ $t('pro.campaignsServe.stop') }}</a-select-option>
                        </a-select>-->
                        <!-- 添加提醒 -->
                        <a-button style="margin: 0 15px" icon="plus" type="primary" @click="openAddModel"
                                  v-show="!loading && !empty">
                            {{ $t('pro.campaignsServe.AddAlert') }}
                        </a-button>
                        <a-input-search :placeholder="$t('pro.campaigns.searchPlaceholder')" @search="onSearch"
                                        v-show="!loading && !empty"/>
                    </div>
                    <add-alert :modal-config="visibleConfig" ref="addAlert" :alert-id='alertId'
                               @setId="setAlertId"></add-alert>
                </div>

                <div>
                    <!-- 分页 table -->
                    <a-spin :spinning="loading">
                        <div class="public-page-box" v-show="!loading && empty">
                            <a-empty
                                    image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original">
                                <span slot="description">{{$t('pro.campaignsServe.emptyAlert')}}</span>
                                <a-button type="primary" icon="plus" @click="openAddModel">
                                    {{$t('pro.filterList.createTips' )}}
                                </a-button>
                            </a-empty>

                            <a-pagination
                                    v-if="!empty"
                                    showSizeChanger
                                    showQuickJumper
                                    :pageSizeOptions="pageSizeOptions"
                                    :pageSize="pagination.size"
                                    :total="pagination.total"
                                    v-model="pagination.current"
                                    @change="handleChange"
                                    @showSizeChange="handleChange"
                            />
                        </div>

                        <a-table v-show="!loading && !empty"
                                 :rowKey="record => record.id"
                                 :loading="loading"
                                 :columns="columns"
                                 :dataSource="data"
                                 :pagination="false"
                                 :scroll="{ x: 1000 }"
                        >
                            <template slot="status" slot-scope="text, record">
                                <a-switch
                                        :checked="record.status === ACTIVE ?true:false"
                                        @change="statusChange(record)"
                                        checkedChildren="ON"
                                        unCheckedChildren="OFF"
                                />
                            </template>

                            <template slot="granularity" slot-scope="text">
                                {{granularityText(text)}}
                            </template>

                            <span slot="campaigns" slot-scope="text,record">
                                {{campaignsText(record.alertCampaign)}}
                            </span>

                            <span slot="details" slot-scope="text,record">
                              <a-tag
                                   :color="record.status == NOTACTIVE ? 'pink': 'blue'">
                                  {{ record.status == NOTACTIVE ? $t('pro.campaignsServe.stop') : $t('pro.campaignsServe.open') }}
                              </a-tag>
                            </span>

                            <a slot="action" slot-scope="text,record" href="javascript:;">
                                <a-button
                                        :title="$t('pro.campaignsServe.edit')"
                                        type="primary"
                                        shape="circle"
                                        icon="edit"
                                        @click="handleEditAlert(record)"
                                        style="margin-right: 5px;"
                                />
                                <a-button
                                        :title="$t('pro.campaignsServe.delete')"
                                        type="primary"
                                        shape="circle"
                                        icon="delete"
                                        @click="onDelete(record.id)"
                                        style="margin-right: 5px;"
                                />
                            </a>

                            <a-table
                                    rowKey="id"
                                    slot="expandedRowRender"
                                    slot-scope="text"
                                    :columns="innerColumns"
                                    :dataSource="handleInnerData(text)"
                                    :pagination="false"
                            >
                                <template slot="alertParametr" slot-scope="text">
                                    {{alertParametrText(text)}}
                                </template>
                                <template slot="alertValue" slot-scope="text,record">
                                    {{record.alertValue ? record.alertValue :" - "}}
                                </template>
                                <template slot="alertRelation" slot-scope="text">
                                    {{alertRelationText(text)}}
                                </template>

                            </a-table>
                        </a-table>
                    </a-spin>
                </div>


            </div>
        </div>
    </div>
</template>

<script>
    import addAlert from '../../components/common/custom/ModelAddAlert'
    import {getAllAlertByPage, delAlert, changeStateAlert} from "@/api/alert-controller"
    import {ACTIVE, NOTACTIVE} from "@/utils/publicStatus"
    import {mapActions} from "vuex";

    export default {
        name: "Alerts",
        components: {
            addAlert,
        },
        data() {
            return {
                visibleConfig: {
                    visibleModal: false,
                },
                data: [],
                alertId: null,
                loading: true,
                empty: false,
                pagination: {
                    size: 10,
                    current: 1,
                    total: 10
                },
                pageSizeOptions: ['10', '20', '30', '40', '50'],
                ACTIVE, NOTACTIVE,
                campaignList: []
            }
        },
        methods: {
            ...mapActions(["GetCampaignList"]),

            setAlertId(alertId) {
                this.alertId = alertId
            },
            //修改监控的状态
            statusChange(record) {
                if (record.status === NOTACTIVE) {
                    record.status = ACTIVE
                } else {
                    record.status = NOTACTIVE
                }
                changeStateAlert({id: record.id,status: record.status})
                    .then(res => {
                        if (res.data.code == 200) {
                            this.$message.info(this.$t('pro.campaigns.statusUpdate'));
                        }
                    })
            },

            handleInnerData(record) {
                let arr = [];
                for(let [key, value] of Object.entries(record)){
                    if (key == "alertValue" || key == "boolOperation" || key == "alertRelation" || key == "alertParametr") {
                        let mapArr = value.split(",") || [];
                        mapArr.map((item, index) => {
                            arr[index]= arr[index] || {};
                            arr[index][key] = item
                        })
                    }
                }
                return arr;

            },

            //点击监控名称编辑
            handleEditAlert(record) {
                this.visibleConfig.visibleModal = true;
                this.alertId = record.id;
            },

            //粒度的显示处理11
            granularityText(text) {

                let textData = this.granularityList.find((e) => {
                    return e['value'] == text.toString();
                });

                let { key } = textData || {};
                return key || ' - ';
            },

            //监控关系字段的显示处理
            alertRelationText(text) {
                let Text = "";
                this.RelationArr.forEach((item) => {
                    if (text == item.value) {
                        Text = item.text
                    }
                });
                return Text
            },

            //监控字段的显示处理
            alertParametrText(text) {
                let Text = "-";
                this.ParametrArr.forEach((item) => {
                   if (item.value == text) {
                       Text = item.text
                   }
                });
                return Text
            },

            //广告活动名字的显示
            campaignsText(id) {
                let campaignName = this.campaignList.find(item => {
                    return item.id == id
                });
                return campaignName ? campaignName['name'] || " - " : " - "
            },

            fetch(params = {}) {
                this.$store.dispatch('GetCampaignList').then(res => {
                    if (res !== null) {
                        this.campaignList = this.getcampaignsList.concat(res);
                        this.empty = false;
                        this.loading = true;
                        params.page = this.pagination.current || 1
                        params.results = this.pagination.size || 10
                        getAllAlertByPage({...params})
                            .then(res => {
                                const data = res.data.data;
                                this.data = data.records;
                                if (data.records.length == 0) {
                                    this.empty = true
                                } else {
                                    this.pagination = data //每页
                                }
                            })
                            .finally(() => {
                                this.loading = false
                            });
                    }

                })
                //console.log(this.$store.getters.campaignList);


            },

            openAddModel() {
                this.alertId = null
                this.visibleConfig.visibleModal = true;
            },

            //模糊查询字段
            onSearch(value) {
                this.fetch({vague: value})
            },

            onDelete(id) {
                let that = this;
                this.$confirm({
                    title: this.$t('pro.campaignsServe.DelAlertTitle'),
                    content: this.$t('pro.campaignsServe.DelAlertContent'),
                    okText: this.$t('pro.public.buttonYes'),
                    okType: "danger",
                    cancelText: this.$t('pro.public.buttonNo'),
                    onOk() {
                        that.loading = true;
                        delAlert({"ids": [id]})
                            .then(res => {
                                if (res.data.code) {
                                    //如果删除成功
                                    that.$message.success(that.$t('pro.viewFilterList.delete_Success'))
                                    that.fetch()
                                }else {
                                    //这里为什么要写2个关闭动画，因为成功会在调用查询，查询里面已经有动画了。所以判断错误要关闭正常的话让查询函数里有关闭处理
                                    that.loading = false;
                                }
                            }).catch(() => { that.loading = false; })
                    },
                    onCancel() {},
                })
            },

            //改变页数的事件
            handleChange(page, pageSize) {
                this.pagination.size = pageSize;
                this.pagination.current = page;
                this.fetch()
            },
        },
        computed: {
            getcampaignsList() {
                return this.$t('pro.reports.alertModalForm.campaignsList')
            },
            granularityList() {
                return this.$t('pro.reports.alertModalForm.granularityList')
            },
            columns() {
                return this.$t('pro.campaignsServe.columns')
            },
            innerColumns() {
                return this.$t('pro.campaignsServe.innerColumns')
            },
            RelationArr() {
                return this.$t('pro.reports.alertModalForm.alertFormRowList')[0].childList[1].options
            },
            ParametrArr() {
                return this.$t('pro.reports.alertModalForm.alertFormRowList')[0].childList[0].options
            },
        },

        created() {
            this.fetch()
        },
    }
</script>

<style scoped>
    .tools-left {
        float: left;
        width: auto;
        display: flex;
        justify-content: space-between
    }
</style>
